package com.yz.hoo;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yz.common.R;
import com.yz.util.UpRSA;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

@RestController
@Api("HooCallBackController相关的api")
public class HooCallBackController {
    private static final Logger logger = LoggerFactory.getLogger(HooCallBackController.class);

    public static String publicStr="MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA6cERcDUahTn9NiBC6eOw+d0hQI265lSwOkA8MnRhS0c6ZZOvmHsi8ElMV1ZuugbI9YIxS55938w7vhSi040bqk27TDvgJsi7wYSrrBz48WeSQ/CfmIZ8gKBA8QPXdvPcbAfdOgfFyEcdmrQGs60+RZCIRZJHWRlXUEI6ZnNPPBVWiRuk2me1tCDqc20pcmZIrs++XCoKkPeHO10iFW1uyqLcjHFVsKZ65gbOzh942SPhC3piT2WbDBYAG8tVGS1MdLpRWkjVUb1SYf2z4JBuaAweCtLUYUyU5YYUoqRb7+bPth50pCcnurfM5SQNjjcDGJiXVFItBMRXOypMPv4jCwkoPImApLpijfh91gdcWmIJNtzMG/JoraIT6xd7XZxeMMr6pBBdUwZykJCJYmytWlgnpxPErzEnbfu6q9hIlFCLBKNNrzh02MzdHp+CosPJzyW02X1YN/0aFQ5AA83mTy21AMosZBtbFNOoMyGa03nUTuBZCPxBSu1M8aTQ9OGCWCqDevwE3GHRofHWydP5XSCS3npjtM1EqTiAXPonSEyqj24kypN7kkMfHaXaHp6o1NdZmg2C3VyPf9sAY1AGfEnMw1LnQ5gzBk2i3HS4Xn5uORJjxnptqvWmz9nVvGHjfT8kjOW6fP3rAg6mTM7+EZw5i0WYqEJyZU+g2iJ/VGcCAwEAAQ==";
    public static String publicSt2="MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEA6cERcDUahTn9NiBC6eOw+d0hQI265lSwOkA8MnRhS0c6ZZOvmHsi8ElMV1ZuugbI9YIxS55938w7vhSi040bqk27TDvgJsi7wYSrrBz48WeSQ/CfmIZ8gKBA8QPXdvPcbAfdOgfFyEcdmrQGs60+RZCIRZJHWRlXUEI6ZnNPPBVWiRuk2me1tCDqc20pcmZIrs++XCoKkPeHO10iFW1uyqLcjHFVsKZ65gbOzh942SPhC3piT2WbDBYAG8tVGS1MdLpRWkjVUb1SYf2z4JBuaAweCtLUYUyU5YYUoqRb7+bPth50pCcnurfM5SQNjjcDGJiXVFItBMRXOypMPv4jCwkoPImApLpijfh91gdcWmIJNtzMG/JoraIT6xd7XZxeMMr6pBBdUwZykJCJYmytWlgnpxPErzEnbfu6q9hIlFCLBKNNrzh02MzdHp+CosPJzyW02X1YN/0aFQ5AA83mTy21AMosZBtbFNOoMyGa03nUTuBZCPxBSu1M8aTQ9OGCWCqDevwE3GHRofHWydP5XSCS3npjtM1EqTiAXPonSEyqj24kypN7kkMfHaXaHp6o1NdZmg2C3VyPf9sAY1AGfEnMw1LnQ5gzBk2i3HS4Xn5uORJjxnptqvWmz9nVvGHjfT8kjOW6fP3rAg6mTM7+EZw5i0WYqEJyZU+g2iJ/VGcCAwEAAQ==";

    public static String test_enc_str = "1:1551691628:12cb4982f5a72e85043b00e0da66625e6cb44bdafdb3b3bdd46d7e44f6f51038b4062b99f37aefd7cd591ca9854e3463682ea374665c3624f26da4704d0085448fbe9ce7843a99886c596a73746a70ad64031fc96d11a94b78e934d3cdc1d92050fd2d464243798fd1c528bb8e4771a52e1c01ef5034364ff759e1b4fdc4088947aa7e2086cfa16bd797603fd5d3f17c4a49f07ea5d53f3cf7a2dbaf321cfba68c600dab7f612ee1e18e72210119bbd2078149283fb626ab697f1bceb056b267482bad6641032bc10f4323762d5d0dcbaf5c4c2ca4f899cd8867c4d5fe27d833367e78e49637166148b3d810fffffd3d5679236f502aa6f2b28ebbf1770652d4857b4b4d6a3336daf863128e6a42fba275f2c6afcbafb0ab06f8739d2e41e8d05b67f4fcc57b1609eb4606b3d75d63f995e923ed15d58781a2136b0d1104dd37c1e65d6e7f64bf699fa6c9eb68e8c041b3ebb5cf51982e385f72b97bbc9e5a50f5f1b4c797b8659d36d04ed569f8be301c37e7b66599d85bcf88f6153a005e35f6dfb14df00a578ef934328d32f071145d41fcfa40c956d8ae03fbfcc1f0e415f6e4f6480006873ebc444323a23b89c5978d2e0b3f97d6968b17c9fb06e2a5dd33bfc37eca957a3d9b8750a3b3e3ff15a1c62386b69983e56118dc53a3f059f416445658a667d32edfd29a1f2ffb1e69738cc59ca69a9e58b801eb5392ef0b37";
    public HooCallBackController() {
    }

    public static void print(Map<String, Object> params) {
        Iterator var1 = params.entrySet().iterator();

        while (var1.hasNext()) {
            Entry<String, Object> entry = (Entry) var1.next();
            logger.info("{}:{}", entry.getKey(), entry.getValue());
        }

    }

    public static void main(String[] args) {
        Map<String, Object> params = new HashMap();
        params.put("sign", "1dc261b54bfda12dfb05dcc3a329e1b3");
        params.put("hoo_sign", "coinName=eos&memo=&msg=success&outOrderId=hoo1891548159251647&sfrom=hoo&txid=76166218c52c9dba30efdae90210412a4aca1997b3c78ea6c4a66b19b5e9f82d");
        HooUtil.verify(params);
        params.clear();
        params.put("sfrom", "DChain");
        params.put("coinName", "eth");
        params.put("num", "1");
        params.put("outOrderId", "hoo1891548234244541");
        params.put("callBack", "http://13.251.220.99:8080/applyAddress_cb");
        params.put("address", "[\"0x000083b20f50963fe11f3006022444d37c23fe15\"]");
        params.put("sign", "50bad2f9d7bf347f1f1525f317c9c4b8");
        HooUtil.verify(params);
    }

    @PostMapping({"AnalysisJson"})
    public R AnalysisJson(@RequestBody BackMessageTestDemo backMessageTestDemo, HttpServletRequest httpRequest) {
        String strAuth = httpRequest.getHeader("auth");
        //这里做切割处理，把header里的auth参数根据":"进行切割，分别为uid，extime，sign
        String strA[] = strAuth.split(":");
        String uid = strA[0];
        String extime = strA[1];
        String sign = strA[2];
        String trx = uid+ ":" + extime + ":" + sign;
        System.out.println("strAuth:" + strAuth);
        try {
            //
            Map<String, String> map = JSON.parseObject(JSONObject.toJSONString(backMessageTestDemo), Map.class);
            Map<String, String> resultMap = new TreeMap<>();
            resultMap.putAll(map);
            String keySort = JSON.toJSONString(resultMap);
            logger.info("keySort:" + keySort);
            String afterStr = uid + ":" + extime + ":" + UpRSA.getSHA256Str(keySort);
            System.out.println("Renew splice afterStr is : " +afterStr );
            PublicKey publicKey = UpRSA.restorePublicKey(UpRSA.decryptBASE64(publicStr));
            String pubKey = UpRSA.RSADecode(publicKey, HooUtil.hexStrToBytes(sign));
            System.out.println("PubKey : "+pubKey);
            if (pubKey.equals(afterStr)) {
                return R.okData(backMessageTestDemo);
            } else {
                System.out.println("The signature is not equal");
                return R.error();
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return R.okData("");
     }
    @ApiOperation("充值地址回调")
    @PostMapping({"chargeCoin_cb"})
    public R chargeCoin_cb(@RequestBody BackMessageTestDemo backMessageTestDemo) {
        logger.info("applyAddress_cb:{}", backMessageTestDemo);
        Map<String, Object> params = null;
        try {
            params = HooUtil.convertToMap(backMessageTestDemo);
        } catch (Exception e) {
            return R.error("转换异常！");
        }
        if (HooUtil.verify(params)) {
            print(params);
            return R.ok("succ");
        } else {
            return R.error("验证签名失败！");
        }

    }

    @ApiOperation("申请地址回调")
    @PostMapping({"applyAddress_cb"})
    public R applyAddress_cb(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        logger.info("applyAddress_cb:{}", params);
        if (HooUtil.verify(params)) {
            print(params);
            return R.ok("succ");
        } else {
            return R.error("验证签名失败！");
        }

    }

    @ApiOperation("自动化交易回调")
    @PostMapping({"applyTransaction_cb"})
    public R applyTransaction_cb(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        logger.info("applyTransaction_cb:{}", params);
        if (HooUtil.verify(params)) {
            print(params);
            return R.ok("succ");
        } else {
            return R.error("验证签名失败！");
        }

    }

    @ApiOperation("eos买内存回调")
    @PostMapping({"applyBuyRam_cb"})
    public R applyBuyRam_cb(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        logger.info("applyBuyRam_cb:{}", params);
        if (HooUtil.verify(params)) {
            print(params);
            return R.ok();
        } else {
            return R.error("验证签名失败！");
        }

    }

    @ApiOperation("eos卖内存回调")
    @PostMapping({"applySellRam_cb"})
    public R applySellRam_cb(@RequestParam Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) {
        logger.info("applySellRam_cb:{}", params);
        if (HooUtil.verify(params)) {
            print(params);
            return R.ok("succ");
        } else {
            return R.error("验证签名失败！");
        }

    }
}
